<template>
  <div>
    <el-dialog :title="title" :visible.sync="open" width="45%" append-to-body :before-close="closeDelDialog">
      <div style="height: 700px; overflow-y: auto">
        <el-form ref="yearForm" :model="yearForm" :rules="rules" label-width="120px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="标题" prop="title">
                <el-input v-model="yearForm.title" placeholder="请输入标题" clearable style="width: 90%"
                  :disabled="!showDelete" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="年度" prop="year">
                <el-date-picker v-model="yearForm.year" type="year" value-format="yyyy" format="yyyy" placeholder="选择年"
                  clearable style="width: 90%" :disabled="!showDelete" />
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="通知内容" prop="noticeContent">
                <editor v-model="yearForm.noticeContent" :min-height="300" accept=".png, .jpg, jpeg"
                  :isMaterialList="true" style="width: 90%" :readOnly="!showDelete" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="" prop="progressFileList">
                <span slot="label">
                  <em style="color:red"> * </em>
                  年检进度计划
                </span>
                <div>
                  <div  v-show="showDelete"  style="display: flex; flex-wrap: wrap; /* 允许子元素换行 */">
                    <el-button class="upload_btn" type="primary" icon="el-icon-upload"
                      v-if="fileMJ == undefined && isFbState" @click="uploadTap">上传文件</el-button>

                    <el-upload v-else  class="upload-file-demo" action="上传的url" ref="progressUpload" :auto-upload="true"
                      :show-file-list='false' :accept="accept" :http-request="progressFile"
                      :file-list="progressFileList">
                      <div style="width: 100%; display: flex">
                        <el-button type="primary" icon="el-icon-upload">上传文件</el-button>
                      </div>
                    </el-upload>
                    <el-select v-if="isFbState" style="margin-left:10px;" v-model="fileMJ" placeholder="请选择文件密级">
                      <el-option v-for="(item, idx) in renyuanOptions" :key="idx" :label="item.dictLabel"
                        :value="item.dictValue"></el-option>
                    </el-select>
                  </div>

                  <div v-for="(item, index) in progressFileList" style="display: flex; margin-left: 1%" :key="index">
                    <span style="padding: 0 5px">{{ item.originalFile }}</span>
                    <p v-if="isFbState" style="border-bottom: 1px solid red;">
                      <span v-for="(i, idx) in renyuanOptions" :key="idx">
                        {{ item.mj == i.dictValue ? i.dictLabel : '' }}
                      </span>
                    </p>
                    <el-button type="text" @click="onPreviewTap(item)" style="margin-left:10px">预览</el-button>
                    <el-button type="text" v-show="showDelete" style="color: #ff0000"
                      @click="deleteTap(item)">删除</el-button>
                  </div>
                </div>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="" prop="requirementsFileList">
                <span slot="label">
                  <em style="color:red"> * </em>
                  相关要求
                </span>
                <div>
                  <div  v-show="showDelete" style="display: flex; flex-wrap: wrap; /* 允许子元素换行 */">
                    <el-button class="upload_btn" type="primary" icon="el-icon-upload"
                      v-if="fileMJ1 == undefined && isFbState" @click="uploadTap1">上传文件</el-button>
                    <el-upload v-else class="upload-file-demo" action="上传的url" ref="requirementsUpload" :auto-upload="true"
                      :show-file-list='false' :accept="accept" :http-request="requirementsFile"
                      :file-list="requirementsFileList">
                      <div style="width: 100%; display: flex">
                        <el-button type="primary" icon="el-icon-upload">上传文件</el-button>
                      </div>
                    </el-upload>
                    <el-select v-if="isFbState" style="margin-left:10px;" v-model="fileMJ1" placeholder="请选择文件密级">
                      <el-option v-for="(item, idx) in renyuanOptions" :key="idx" :label="item.dictLabel"
                        :value="item.dictValue"></el-option>
                    </el-select>
                  </div>
                  <div v-for="(item, index) in requirementsFileList" style="display: flex; margin-left: 1%" :key="index">
                    <span style="padding: 0 5px">{{ item.originalFile }}</span>
                    <p v-if="isFbState" style="border-bottom: 1px solid red;">
                      <span v-for="(i, idx) in renyuanOptions" :key="idx">
                        {{ item.mj == i.dictValue ? i.dictLabel : '' }}
                      </span>
                    </p>
                    <el-button type="text" @click="onPreviewTap(item)" style="margin-left:10px">预览</el-button>
                    <el-button type="text" v-show="showDelete" style="color: #ff0000"
                      @click="deleteTap(item)">删除</el-button>
                  </div>
                </div>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="其他附件">
                <div>
                <div   v-show="showDelete" style="display: flex; flex-wrap: wrap; /* 允许子元素换行 */">
                  <el-button class="upload_btn" type="primary" icon="el-icon-upload"
                      v-if="fileMJ2 == undefined && isFbState" @click="uploadTap2">上传文件</el-button>
                  <el-upload v-else class="upload-file-demo" action="上传的url" ref="otherUpload" :auto-upload="true"
                    :show-file-list='false' :accept="accept" :http-request="otherFile"
                    :file-list="otherFileList">
                    <div style="width: 100%; display: flex">
                      <el-button type="primary" icon="el-icon-upload">上传文件</el-button>
                    </div>
                  </el-upload>
                  <el-select v-if="isFbState" style="margin-left:10px;" v-model="fileMJ2" placeholder="请选择文件密级">
                      <el-option v-for="(item, idx) in renyuanOptions" :key="idx" :label="item.dictLabel"
                        :value="item.dictValue"></el-option>
                    </el-select>
                </div>
                  <div v-for="(item, index) in otherFileList" style="display: flex; margin-left: 1%" :key="index">
                    <span style="padding: 0 5px">{{ item.originalFile }}</span>
                    <p v-if="isFbState" style="border-bottom: 1px solid red;">
                      <span v-for="(i, idx) in renyuanOptions" :key="idx">
                        {{ item.mj == i.dictValue ? i.dictLabel : '' }}
                      </span>
                    </p>
                    <el-button type="text" @click="onPreviewTap(item)" style="margin-left:10px">预览</el-button>
                    <el-button type="text" v-show="showDelete" style="color: #ff0000"
                      @click="deleteTap(item)">删除</el-button>
                  </div>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer" v-show="showDelete">
        <el-button type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="resetlogin">重 置</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="viewTitle" :visible.sync="viewOpen" width="45%" append-to-body>
      <div>
        <!--
         文件预览
         1、修改添加文件预览istype="1"
         2、查看组件详情istype="2"
         -->
        <FilePreview v-if="item" :item="item" :istype="istype" :moudle="1"></FilePreview>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { uploadFile, deleteFile, addNotice, updateNotice } from "@/api/archive/supervision/annualInspectionNotice";
import FilePreview from "@/views/archive/supervision/supervises/filePreview";
import { getDicts_archive } from '@/api/archive/dict/dictManageData'
import { fbstat } from "@/api/archive/fileCollection/offlinReception.js";
import {
  getdamjbyrymj
} from "@/api/archive/fileCollection/offlinReception.js";
export default {
  name: "notice",
  props: ['title', 'open', 'dataInfo', 'showDelete','type'],
  components: { FilePreview },
  data() {
    // const checkProgressFileList = (rule, value, callback) => {
    //   if (this.progressFileList.length === 0) {
    //     callback(new Error('请上传文件'));
    //   } else {
    //     callback();
    //   }
    // };
    // const checkRequirementsFileList = (rule, value, callback) => {
    //   if (this.requirementsFileList.length === 0) {
    //     callback(new Error('请上传文件'));
    //   } else {
    //     callback();
    //   }
    // };
    return {
      yearForm: {
        title: undefined,
        year: undefined,
        noticeContent: undefined,
        attachmentsList: []
      },
      rules: {
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" },
        ],
        year: [
          { required: true, message: "年度不能为空", trigger: "blur" },
        ],
        noticeContent: [
          { required: true, message: "通知内容不能为空", trigger: "blur" },
        ],
        // progressFileList: [
        //   { validator: checkProgressFileList, trigger: "blur" }
        // ],
        // requirementsFileList: [
        //   { validator: checkRequirementsFileList, trigger: "blur" }
        // ],
      },
      progressFileList: [],
      requirementsFileList: [],
      otherFileList: [],
      viewOpen: false,
      viewTitle: '',
      item: '',
      istype: '1',
      accept: '.doc, .docx, .xls, .xlsx, .txt, .pdf, .gif, .jpeg, .png',
      renyuanOptions: [],//密级下拉列表
      isFbState: false,
      fileMJ: undefined,
      fileMJ1:undefined,
      fileMJ2:undefined
    }
  },
  watch: {
    dataInfo: {
      handler(val) {
        this.$nextTick(() => {
          this.$set(this, 'yearForm', JSON.parse(JSON.stringify(val)));
          this.yearForm.attachmentsList = val.attachmentsList.map(item => {
            // 为每个对象添加 docType 属性，并赋值为 originalFile后缀
            item.docType = this.getType(item.originalFile)
            return item;
          });
          this.progressFileList = this.yearForm.attachmentsList.filter(item => item.fileType == '1')
          this.requirementsFileList = this.yearForm.attachmentsList.filter(item => item.fileType == '2')
          this.otherFileList = this.yearForm.attachmentsList.filter(item => item.fileType == '3')
        })
      },
      deep: true
    }
  },
  created() {
    fbstat().then(res => {  //false=不是分保，true=是分保
      this.isFbState = res.data
      if (this.isFbState) {
        //密级下拉列表
        getDicts_archive("MJ").then(res => { //人员密级
          getdamjbyrymj().then(resdata => { //此接口没有返回dictLabel，需要组装接口
            var mjdata = [];
            for (var i in resdata.data) {
              for (var j in res.data) {
                if (resdata.data[i].daMj == res.data[j].dictValue) {
                  mjdata.push(res.data[j])
                }
              }
            }

            this.renyuanOptions = mjdata
          })
        })
      }
    })
  },
  methods: {
    uploadTap() {
      if (this.fileMJ == undefined) {
        this.$message.warning(`请选择密级`);
        return false
      }
    },
    uploadTap1(){
      if (this.fileMJ1 == undefined) {
        this.$message.warning(`请选择密级`);
        return false
      }
    },
    uploadTap2(){
      if (this.fileMJ2 == undefined) {
        this.$message.warning(`请选择密级`);
        return false
      }
    },
    // 开始上传文件
    // 年检进度计划
    progressFile(content) {
      this.file = content.file
      const formData = new FormData();
      formData.append("file", content.file);
      formData.append("type", '1');
      if(this.fileMJ){
        formData.append("mj", this.fileMJ);
      }

      if (this.yearForm.id != undefined) {
        formData.append("id", this.yearForm.id);
      }
      uploadFile(formData).then(response => {
        this.progressFileList.push({
          filePath: response.data.filePath,
          id: response.data.id,
          fileName: response.data.fileName,
          fileType: response.data.fileType,
          originalFile: response.data.originalFile,
          docType: this.getType(response.data.originalFile),
          mj: response.data.mj
        })
      })
    },
    // 相关要求
    requirementsFile(content) {
      this.file = content.file
      const formData = new FormData();
      formData.append("file", content.file);
      formData.append("type", '2');
      if(this.fileMJ1){
        formData.append("mj", this.fileMJ1);
      }
      if (this.yearForm.id != undefined) {
        formData.append("id", this.yearForm.id);
      }
      uploadFile(formData).then(response => {
        this.requirementsFileList.push({
          filePath: response.data.filePath,
          id: response.data.id,
          fileName: response.data.fileName,
          fileType: response.data.fileType,
          originalFile: response.data.originalFile,
          docType: this.getType(response.data.originalFile),
          mj: response.data.mj
        })
      })
    },
    // 其他附件
    otherFile(content) {
      this.file = content.file
      const formData = new FormData();
      formData.append("file", content.file);
      formData.append("type", '3');
      if(this.fileMJ2){
        formData.append("mj", this.fileMJ2);
      }
      if (this.yearForm.id != undefined) {
        formData.append("id", this.yearForm.id);
      }
      uploadFile(formData).then(response => {
        this.otherFileList.push({
          filePath: response.data.filePath,
          id: response.data.id,
          fileName: response.data.fileName,
          fileType: response.data.fileType,
          originalFile: response.data.originalFile,
          docType: this.getType(response.data.originalFile),
          mj: response.data.mj
        })
      })
    },
    // 获取文件类型
    getType(fileName) {
      let arr = fileName.split('.');
      let result = arr.pop();
      return result;
    },
    closeDelDialog() {
      this.reset();
      this.$emit('closeDelDialog')
    },
    // 重置按钮
    resetlogin() {
      this.reset();
      this.resetForm("yearForm");
    },
    // 表单重置
    reset() {
      this.yearForm = {
        title: undefined,
        year: undefined,
        noticeContent: undefined,
        attachmentsList: []
      }
      this.progressFileList = []
      this.requirementsFileList = []
      this.otherFileList = []
    },
    submitForm() {
      this.$refs["yearForm"].validate(valid => {
        if (valid) {
          this.yearForm.attachmentsList = this.yearForm.attachmentsList.filter(item => item.fileType != '1' && item.fileType != '2' && item.fileType != '3')
          if (this.progressFileList.length != 0) {
            this.yearForm.attachmentsList.push(...this.progressFileList)
          } else {
            this.$modal.msgWarning('请上传年检进度计划');
            return false;
          }
          if (this.requirementsFileList.length != 0) {
            this.yearForm.attachmentsList.push(...this.requirementsFileList)
          } else {
            this.$modal.msgWarning('请上传相关要求');
            return false;
          }
          if (this.otherFileList.length != 0) {
            this.yearForm.attachmentsList.push(...this.otherFileList)
          }
          if (this.yearForm.id != undefined) {
          //  this.yearForm.noticeContent = encodeURIComponent(this.yearForm.noticeContent)
            updateNotice(this.yearForm).then(res => {
              this.$modal.msgSuccess('修改成功')
              this.closeDelDialog();
            })
          } else {
          //  this.yearForm.noticeContent = encodeURIComponent(this.yearForm.noticeContent)
            this.yearForm.type = this.type;
            addNotice(this.yearForm).then(res => {
              this.$modal.msgSuccess('添加成功')
              this.closeDelDialog();
            })
          }
        }
      });
    },
    // 预览
    onPreviewTap(item) {
      if (item.docType == 'OFD' || item.docType == 'ofd') {
        this.$modal.msgWarning('OFD文件不支持预览')
      } else {
        this.viewTitle = item.originalFile
        this.viewOpen = true
        this.item = item
      }
    },
    // 删除
    deleteTap(item) {
      var form = {
        noticesId: this.dataInfo.id,
        attachmentsId: item.id,
        attachmentsType: item.fileType
      }
      this.$modal.confirm('是否确认删除名为"' + item.originalFile + '"的附件？').then(function () {
        return deleteFile(form)
      }).then(res => {
        this.getFileList(form)
        this.$modal.msgSuccess('删除成功')
      }).catch(() => { });
    },
    getFileList(form) {
      if (form.attachmentsType == '1') {
        this.progressFileList = this.progressFileList.filter(item => item.id !== form.attachmentsId);
      }
      if (form.attachmentsType == '2') {
        this.requirementsFileList = this.requirementsFileList.filter(item => item.id !== form.attachmentsId);
      }
      if (form.attachmentsType == '3') {
        this.otherFileList = this.otherFileList.filter(item => item.id !== form.attachmentsId);
      }
    }
  }
}
</script>

<style scoped></style>
